import { ReactElement, useState, useEffect, useRef, RefObject } from 'react'
import { Modal, Form, Select, FormInstance, message } from 'antd'
import { AccountSchema } from '@components/schema/account'
import { getPersonListRequest, addRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import { WorkPerformanceSchema } from '@src/components/schema/performanceSchema'
const { Item } = Form
const { Option } = Select

// 初始化人员列表
async function initPersons (setList: (v: AccountSchema[]) => void): Promise<void> {
  const [e, d] = await awaitWrap(getPersonListRequest())
  if (e === null && d instanceof Array) {
    setList(d)
  }
}

// 添加操作
async function addHandle (performanceid: string, d: { [k: string]: any }, refreshData: () => void, hide: () => void): Promise<void> {
  const h = message.loading('提交中')
  d.name = d.realname
  delete d.realname
  const [e] = await awaitWrap(addRequest(performanceid, d))
  h()
  if (e === null) {
    hide()
    refreshData()
  }
}

function changePerson (name: string, list: AccountSchema[], formRef: RefObject<FormInstance>): void {
  for (let i = 0; i < list.length; i++) {
    if (list[i].realname === name) {
      formRef.current?.setFieldsValue({ accountid: list[i].id })
    }
  }
}

interface Props {
  performanceid: string
  visible: boolean
  data: WorkPerformanceSchema | null
  hide: () => void
  refreshData: () => void
}

function Main ({ visible, hide, data, performanceid, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  const [list, setList] = useState<AccountSchema[]>([])
  useEffect(() => {
    initPersons(setList).catch(e => console.error(e))
  }, [])
  useEffect(() => {
    const c = formRef.current
    if (c !== null && data !== null) {
      c.setFieldsValue(data)
    }
  }, [formRef, data])
  useEffect(() => {
    const c = formRef.current
    if (!visible && c !== null) {
      c.resetFields()
    }
  }, [visible, formRef])
  return (
    <Modal visible={visible} title={'添加人员'} maskClosable={false} onCancel={hide} onOk={() => formRef.current?.submit()}>
      <Form ref={formRef} labelCol={{ flex: '88px' }} onFinish={async (d) => await addHandle(performanceid, d, refreshData, hide)}>
        <Item noStyle name='id'><span /></Item>
        <Item noStyle name='accountid'><span /></Item>
        <Item label='姓名' name='realname' rules={[{ required: true, message: '人员不能为空' }]}>
          <Select placeholder='请选择' showSearch onChange={(v: string) => changePerson(v, list, formRef)}>
            {list.map((li, i) => {
              return <Option key={i} value={li.realname}>{li.realname}</Option>
            })}
          </Select>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
